package com.xindaoapp.happypet;

// Static wrapper library around AsyncHttpClient

/**
 * 访问网络工具
 */
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.utils.CommonLog;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.xdConfig;

public class XDHttpClient {
    protected static CommonLog log = new CommonLog();
    public static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String api, RequestParams params,
            AsyncHttpResponseHandler responseHandler) {

        String absoluteUrl = getAbsoluteUrl(api);
        if (absoluteUrl.indexOf("?") != -1) {
            log.i(getAbsoluteUrl(api) + "&" + params.toString());
        } else {
            log.i(getAbsoluteUrl(api) + "?" + params.toString());
        }
        if (ConstantsValue.cookieStore != null) {
            client.setCookieStore(ConstantsValue.cookieStore);
        }
        client.get(getAbsoluteUrl(api), params, responseHandler);
    }

    public static void get2(String api, RequestParams params,
            AsyncHttpResponseHandler responseHandler) {
        if (ConstantsValue.cookieStore != null) {
            client.setCookieStore(ConstantsValue.cookieStore);
        }
        client.get(api, params, responseHandler);
    }

    public static void post(String api, RequestParams params,
            AsyncHttpResponseHandler responseHandler) {
        if (ConstantsValue.cookieStore != null) {
            client.setCookieStore(ConstantsValue.cookieStore);
        }
        log.i(getAbsoluteUrl(api) + params.toString());
        client.post(getAbsoluteUrl(api), params, responseHandler);
    }

    public static void post2(String api, RequestParams params,
            AsyncHttpResponseHandler responseHandler) {
        // 检查网络
        if (CommonUtil.isNetworkAvailable(HappyPetApplication.get().getApplicationContext()) == 0) {
            responseHandler.onFailure(null, "no have network");
        } else {
            if (ConstantsValue.cookieStore != null) {
                client.setCookieStore(ConstantsValue.cookieStore);
            }
            log.i(getAbsoluteUrl(api) + params.toString());
            client.post(api, params, responseHandler);
        }

    }

    public static String getAbsoluteUrl(String relativeUrl) {
        return xdConfig.HOST_URL + relativeUrl;
    }

}
